import { ActivityList, Activity } from './cpm'
function findKeyPath (edges) {
  const raw = edges.map(edge => {
    return {
      id: edge.source,
      duration: edge.label,
      predecessors: edges.filter(item => item.source === edge.target).map(i => i.source)
    }
  })
  console.log('raw::', raw)
  let dist = []
  let hash = {}
  raw.forEach(item => {
    let d = hash[item.id]
    if (d) {
      d.predecessors = Array.from(new Set([...d.predecessors, ...item.predecessors]))
      return
    }
    dist.push(item)
    hash[item.id] = item
  })
  const table = new ActivityList()
  dist.forEach(act => {
    table.addActivity(new Activity(act))
  })
  const activities = table.getCriticalPath(edges[edges.length - 1].source)
  return flatten(activities)
}
function flatten (arr, res = []) {
  res.push({ id: arr.id, duration: arr.duration, est: arr.est, lst: arr.lst })
  return arr.predecessors.length === 0 ? res : flatten(arr.predecessors[0], res)
}
function findKeyPathForName (edges) {
  const raw = edges.map(edge => {
    return {
      id: edge.source,
      duration: edge.label,
      predecessors: edges.filter(item => item.source === edge.target).map(i => i.source)
    }
  })
  let dist = []
  let hash = {}
  raw.forEach(item => {
    let d = hash[item.id]
    if (d) {
      d.predecessors = Array.from(new Set([...d.predecessors, ...item.predecessors]))
      return
    }
    dist.push(item)
    hash[item.id] = item
  })
  const table = new ActivityList()
  dist.forEach(act => {
    table.addActivity(new Activity({
      id: act.id,
      duration: Number(act.duration),
      predecessors: act.predecessors
    }))
  })
  const activities = table.getCriticalPath('Start')
  return flatten(activities)
}
export default { findKeyPath, findKeyPathForName }
